// pages2/pages/mall/submit/index.js
const $api = require('../../../../request/api').API;
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import * as Storage from '../../../../utils/storage';
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [],
    info: {},
    addressInfo: null,
    goodsFormList: [],
    formList: [],
    showAddress: false //是否显示地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const info = JSON.parse(decodeURIComponent(options.query));
    let { goods, attr, addressInfo } = info;
    this.activeTime(goods);
    goods = [{ ...goods, nums: 1 }];
    this.judgeTimeout(goods);
    info.linkUrl = info.linkUrl ? [...info.linkUrl].join(' ') : '';

    this.setData({
      goodsList: goods,
      info,
      addressInfo
    });
    if (attr) this.formatFormInfo(attr);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  async onReady() {
    const {
      goodsList,
      info: { beeperId },
      addressInfo
    } = this.data;
    if (!addressInfo) return;
    this.addressCpm = this.selectComponent('#address');
    this.setData({
      showAddress: await this.addressCpm.init({ beeperId, info: goodsList[0], addressInfo })
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  async formatFormInfo(attr) {
    let arr = attr['1'] || [];
    let goodsFormList = [];
    const {
      goodsList: [{ goodsId, serverId }]
    } = this.data;
    for (let key in arr) {
      arr[key].forEach(item => {
        !item.goodsId && (item.goodsId = goodsId);
        !item.serverId && (item.serverId = serverId);
      });
      // 以下是对比本地存储的属性属性attrId一样就获取本地存储的值
      const obj = {
        name: arr[key][0].serverName || arr[key][0].goodsName,
        list: arr[key],
        introduce: arr[key][0].introduce
      };
      goodsFormList.push(obj);
    }
    this.setData({
      formList: attr['2'] || [],
      goodsFormList
    });
  },
  // 修改表单数据
  modifyFormData(e) {
    // const { val, activeIndex, index } = e.detail
    // this.data.formList[activeIndex][index].value = val
    this.setData({
      formList: e.detail.formList
    });
  },
  // 修改产品表单数据
  modifyFormData2(e) {
    const { goodsFormList } = this.data;
    goodsFormList[e.currentTarget.dataset.index].list = e.detail.formList[0];
    this.setData({
      goodsFormList
    });
  },
  // 判断哪些产品不在销售时间内
  judgeTimeout(goodsList) {
    goodsList.forEach(item => {
      let res = null;
      if (!item.goodsHours || (item.goodsHours && !item.goodsHours.length)) {
        return;
      }
      res = item.goodsHours.some(item => {
        let time = new Date();
        let begin = new Date();
        let end = new Date();
        const arr = item.beginHours.split(':').map(item => Number(item));
        const arr2 = item.endHours.split(':').map(item => Number(item));
        begin.setHours(arr[0]);
        begin.setMinutes(arr[1]);
        end.setHours(arr2[0]);
        end.setMinutes(arr2[1]);
        return time.getTime() > begin.getTime() && time.getTime() < end.getTime();
      });
      if (!res) {
        item.saleState = 0;
      }
    });
    // this.setData({
    //   goodsList,
    // })
  },
  //需要判断是不是活动时间
  activeTime(val) {
    val = Array.isArray(val) ? val : [val]; //拼接一个数组好计算
    val.forEach(item => {
      if (!item.active) return;
      let { beginDate, endDate, activePrice } = item.active;
      beginDate = getDatetime(beginDate).getTime();
      endDate = getDatetime(endDate).getTime();
      let nowDate = new Date().getTime();
      if (nowDate > beginDate && nowDate < endDate) {
        item.activeDiscount = parseFloat(((activePrice / item.price) * 10).toFixed(2)) || 0.01;
      } else {
        item.activeDiscount = '';
      }
    });
  },
  addNum(e) {
    let {
      item: { nums },
      index
    } = e.currentTarget.dataset;
    const { goodsList } = this.data;
    goodsList[index].nums = ++nums;
    this.setData({
      goodsList
    });
  },
  subNum(e) {
    let {
      item: { nums },
      index
    } = e.currentTarget.dataset;
    const { goodsList } = this.data;
    goodsList[index].nums = nums <= 1 ? 1 : --nums;
    this.setData({
      goodsList
    });
  },
  async submitOrder() {
    let {
      goodsList,
      info: { beeperId, id, btnName, orderSource, sourceId },
      goodsFormList,
      formList
    } = this.data;
    const { variantId, nums, goodsType, stock, saleState, goodsHours, goodsId, combineId } = goodsList[0];
    if (goodsFormList.length > 0) {
      for (let key in goodsFormList) {
        if (!this.selectComponent('.custom-form' + key).validate()) {
          return;
        }
      }
    }
    if (formList.length > 0 && !this.selectComponent('#custom-form').validate()) {
      return;
    }
    if (!stock) {
      return Toast.fail('暂无库存');
    }
    if (saleState != 2 && goodsHours && goodsHours.length) {
      return Toast.fail('不在可售时间内');
    }

    if (nums <= 0) {
      return Toast.fail('请添加一件产品');
    }
    let params = {
      orderAttrs: [...goodsFormList.flatMap(item => item.list), ...formList.flat()],
      beeperId,
      btnId: id,
      nums,
      openId: wx.getStorageSync(Storage.USER_OPEN_ID)
    };

    let harvestAddressId = await this.addressCpm.validate();
    if (!harvestAddressId) return;
    params.harvestAddressId = harvestAddressId;

    await Dialog.confirm({
      title: '提示',
      message: '确定下单？',
      zIndex: '999'
    });

    if (combineId) {
      Object.assign(params, { combineId });
    } else {
      Object.assign(params, { variantId, goodsId, goodsType });
      if (orderSource) params.orderSource = orderSource;
      if (sourceId) params.sourceId = sourceId;
      if (btnName) params.btnName = btnName;
    }
    Toast.loading({
      message: '正在下单',
      forbidClick: true,
      mask: true,
      duration: 0
    });
    let res = await $api.simpleOrder(params);
    res = res.data.data;
    try {
      if (res) {
        Toast.clear();
        await wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.paySign
        });
      }
      Toast.success({
        message: '下单成功',
        forbidClick: true,
        mask: true
      });
    } finally {
      setTimeout(() => {
        app.globalData.beeperOrderId = beeperId;
        wx.switchTab({
          url: '/pages/order/index'
        });
      }, 2000);
      // this.close()
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
